import 'dart:io';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/common/http/http_interceptor.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/startup/config/app_start.dart';
import 'package:tracker/startup/env/env.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/global_context.dart';
import 'package:tracker/theme/app_theme.dart';

import 'common/log/x_logger.dart';

Future<void> _initAppConfig() async {
  print('Appstart 初始化');
  try {
    // await JPushUtils.initJPush();
    print('JPushUtils 初始化');

    await AppStart.initConfig();
    // 初始化完成后，可以触发状态更新（例如通知 Provider）
    // await AppStart.showMapConfig();   // 控制地图与huawei 的显示
    // 初始化极光推送

    // 例如：通过 Provider 监听配置变化
  } catch (e) {
    // 处理错误
    print('Appstart 初始化失败: $e');
  }
}

void main() async {
  // 不加这个强制横/竖屏会报错
  WidgetsFlutterBinding.ensureInitialized();
  // 禁止横屏
  await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  Env.initEnvConfig();
  await AppStart.initConfig();
  // 等待sp初始化完成后再运行app。
  // sp初始化时间 release模式下30ms左右，debug模式下100多ms。
  await SpUtil.getInstance();

  if (Platform.isAndroid) {
    final isAgree = SpUtil.getBool('hasAgreed') ?? false;
    XLogger.debug('isAgree :$isAgree');
    if (isAgree) {
      await _initAppConfig();
    }
  }else {
    await _initAppConfig();
  }

  NetOptions.instance
      .setBaseUrl(Env.envConfig.apiBaseUrl)
      .setConnectTimeout(const Duration(seconds: 5))
      // .setHttpDecoder(MyHttpDecoder.getInstance())
      .addInterceptor(HttpInterceptor())
      .enableLogger(true)
      .create();
  runApp(const ProviderScope(child: MyApp()));
}

class MyApp extends ConsumerWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        // 点击空白处收起键盘
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: MaterialApp.router(
        key: NavigationService.navigatorKey,
        title: Env.envConfig.appName,
        locale: const Locale('zh', 'CN'),
        localizationsDelegates: const [
          // 本地化的代理类
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: const [
          // 支持的本地化语言
          Locale('zh', 'CN'),
        ],
        themeMode: ThemeMode.light,
        darkTheme: ThemeData.light(),
        // 关闭debug标签
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          brightness: Brightness.light,
          useMaterial3: true,
          visualDensity: VisualDensity.adaptivePlatformDensity,
          colorScheme: ColorScheme.fromSeed(
            seedColor: AppTheme.themeConfig.primaryColor,
            brightness: Brightness.light,
          ).copyWith(
            surfaceTint: Colors.white,
            primary: AppTheme.themeConfig.primaryColor,
            secondary: AppTheme.themeConfig.accentColor,
          ),
          scaffoldBackgroundColor: AppTheme.themeConfig.greyBgColor,
          dividerColor: AppTheme.themeConfig.dividerColor,
          dividerTheme: DividerThemeData(
            color: AppTheme.themeConfig.dividerColor,
            thickness: 0.8,
            space: 0.8,
          ),
          appBarTheme: AppBarTheme(
            backgroundColor: AppTheme.themeConfig.navBarColor,
            foregroundColor: AppTheme.themeConfig.primaryTextColor,
            centerTitle: true,
            elevation: 0,
            scrolledUnderElevation: 0,
            titleTextStyle: TextStyle(
              color: AppTheme.themeConfig.primaryTextColor,
              fontSize: 18,
              fontWeight: FontWeight.w600,
              letterSpacing: 0.2,
            ),
            iconTheme: IconThemeData(color: AppTheme.themeConfig.primaryTextColor),
          ),
          textTheme: TextTheme(
            displayLarge: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 44, fontWeight: FontWeight.w600, letterSpacing: -0.5),
            displayMedium: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 38, fontWeight: FontWeight.w600, letterSpacing: -0.3),
            displaySmall: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 32, fontWeight: FontWeight.w600),
            headlineMedium: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 24, fontWeight: FontWeight.w600),
            headlineSmall: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 20, fontWeight: FontWeight.w600),
            titleLarge: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 18, fontWeight: FontWeight.w600),
            titleMedium: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 16, fontWeight: FontWeight.w500),
            titleSmall: TextStyle(color: AppTheme.themeConfig.secondaryTextColor, fontSize: 14, fontWeight: FontWeight.w500),
            bodyLarge: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 16, letterSpacing: 0.1),
            bodyMedium: TextStyle(color: AppTheme.themeConfig.primaryTextColor, fontSize: 14, letterSpacing: 0.1),
            bodySmall: TextStyle(color: AppTheme.themeConfig.secondaryTextColor, fontSize: 12, letterSpacing: 0.2),
            labelLarge: TextStyle(color: AppTheme.themeConfig.infoTextColor, fontSize: 14, fontWeight: FontWeight.w500),
          ),
          elevatedButtonTheme: ElevatedButtonThemeData(
            style: ButtonStyle(
              elevation: const MaterialStatePropertyAll(0),
              padding: const MaterialStatePropertyAll(EdgeInsets.symmetric(horizontal: 16, vertical: 12)),
              shape: MaterialStatePropertyAll(
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
              ),
              foregroundColor: MaterialStatePropertyAll(Colors.white),
              backgroundColor: MaterialStatePropertyAll(AppTheme.themeConfig.primaryColor),
            ),
          ),
          textButtonTheme: TextButtonThemeData(
            style: ButtonStyle(
              padding: const MaterialStatePropertyAll(EdgeInsets.symmetric(horizontal: 8, vertical: 8)),
              foregroundColor: MaterialStatePropertyAll(AppTheme.themeConfig.primaryColor),
              overlayColor: MaterialStatePropertyAll(AppTheme.themeConfig.primaryColor.withOpacity(0.06)),
              shape: MaterialStatePropertyAll(
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              ),
            ),
          ),
          outlinedButtonTheme: OutlinedButtonThemeData(
            style: ButtonStyle(
              padding: const MaterialStatePropertyAll(EdgeInsets.symmetric(horizontal: 14, vertical: 12)),
              side: MaterialStatePropertyAll(BorderSide(color: AppTheme.themeConfig.primaryColor.withOpacity(0.4))),
              foregroundColor: MaterialStatePropertyAll(AppTheme.themeConfig.primaryColor),
              shape: MaterialStatePropertyAll(
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
              ),
            ),
          ),
          inputDecorationTheme: InputDecorationTheme(
            isDense: true,
            filled: true,
            fillColor: Colors.white,
            contentPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 14.0),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: BorderSide(color: AppTheme.themeConfig.dividerColor),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: BorderSide(color: AppTheme.themeConfig.dividerColor),
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(14),
              borderSide: BorderSide(color: AppTheme.themeConfig.primaryColor, width: 1.2),
            ),
            hintStyle: TextStyle(color: AppTheme.themeConfig.infoTextColor),
          ),
          bottomNavigationBarTheme: BottomNavigationBarThemeData(
            selectedItemColor: AppTheme.themeConfig.primaryColor,
            unselectedItemColor: AppTheme.themeConfig.infoTextColor,
            type: BottomNavigationBarType.fixed,
            elevation: 8,
            backgroundColor: Colors.white,
            selectedLabelStyle: const TextStyle(fontWeight: FontWeight.w600),
          ),
          tabBarTheme: TabBarTheme(
            labelColor: AppTheme.themeConfig.primaryColor,
            unselectedLabelColor: AppTheme.themeConfig.infoTextColor,
            indicatorColor: AppTheme.themeConfig.primaryColor,
            dividerColor: Colors.transparent,
            labelStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
            unselectedLabelStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
          ),
          cardTheme: CardTheme(
            color: Colors.white,
            elevation: 2,
            margin: const EdgeInsets.all(0),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          ),
          snackBarTheme: SnackBarThemeData(
            backgroundColor: AppTheme.themeConfig.primaryColor,
            contentTextStyle: const TextStyle(color: Colors.white),
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
          chipTheme: ChipThemeData(
            backgroundColor: AppTheme.themeConfig.navBarColor,
            disabledColor: AppTheme.themeConfig.disableTextColor,
            selectedColor: AppTheme.themeConfig.primaryColor.withOpacity(0.15),
            secondarySelectedColor: AppTheme.themeConfig.primaryColor.withOpacity(0.15),
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
            labelStyle: TextStyle(color: AppTheme.themeConfig.primaryTextColor),
            secondaryLabelStyle: const TextStyle(color: Colors.white),
            brightness: Brightness.light,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        ),
        routerConfig: RouterManager.routerConfig,
        builder: EasyLoading.init(builder: (context, child) {
          return MediaQuery(
            data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
            child: child ?? Container(),
          );
        }),
      ),
    );
  }
}
